﻿using System.Net.Mail;
using System.Net;

namespace Journeo_backend.Services.Implementations
{
    public class EmailService : IEmailService
    {
        private readonly IConfiguration _configuration;

        public EmailService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task SendEmailAsync(string to, string subject, string body)
    {
        try
        {
            using var message = new MailMessage();
            message.From = new MailAddress(_configuration["Email:From"]);
            message.To.Add(new MailAddress(to));
            message.Subject = subject;
            message.Body = body;
            message.IsBodyHtml = false;

            // 可以添加一个更美观的HTML模板
            string htmlBody = $@"
                <div style='font-family: Arial, sans-serif; padding: 20px; max-width: 600px; margin: 0 auto;'>
                    <h2 style='color: #333;'>验证码</h2>
                    <p style='color: #666; font-size: 16px;'>{body}</p>
                    <p style='color: #999; font-size: 14px; margin-top: 20px;'>
                        此邮件由系统自动发送，请勿回复。
                    </p>
                </div>";
            message.Body = htmlBody;
            message.IsBodyHtml = true;

            using var client = new SmtpClient(_configuration["Email:SmtpServer"])
            {
                Port = int.Parse(_configuration["Email:Port"]),
                Credentials = new NetworkCredential(
                    _configuration["Email:Username"], 
                    _configuration["Email:SmtpCode"]  // 使用SMTP授权码
                ),
                EnableSsl = true
            };

            await client.SendMailAsync(message);
        }
        catch (Exception ex)
        {
            throw new Exception("Failed to send email", ex);
        }
    }
    }
}
